extends Node3D

@onready var turretmid: MeshInstance3D = $turretbase/turretmid
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var turretbase: MeshInstance3D = $turretbase
@onready var cannon: Node3D = $turretbase/Cannon


@export var projectile: PackedScene 
@export var max_turret_range: float = 10.0

var target: PathFollow3D
var enemy_path: Path3D

func _physics_process(delta: float) -> void:
	target = find_best_target()#注意，全局变量局部使用时不要再加var,否则会变成局部变量
	if target != null:
		turretbase.look_at(target.global_position, Vector3.UP, true)
	
func _on_timer_timeout() -> void:
	if target != null:
		var shot = projectile.instantiate()
		add_child(shot)
		shot.global_position = turretmid.global_position
		shot.direction = turretbase.global_transform.basis.z
		animation_player.play("fire")
	
func find_best_target() -> PathFollow3D:
	var best_target = null
	var best_progess: float = 0.0
	for enemy in enemy_path.get_children():
		if enemy is PathFollow3D:
			var enemy_distance = global_position.distance_to(enemy.global_position)
			if enemy_distance < max_turret_range:
				if enemy.progress > best_progess:
					best_target = enemy
					best_progess = enemy.progress
	return best_target
